package com.darker.secking.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.darker.secking.entity.SeckingOrder;
import com.darker.secking.entity.User;
import com.darker.secking.mapper.SeckingOrderMapper;
import com.darker.secking.service.ISeckingOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author darker
 * @since 2022-10-06
 */
@Service
public class SeckingOrderServiceImpl extends ServiceImpl<SeckingOrderMapper, SeckingOrder> implements ISeckingOrderService {
    @Autowired
    SeckingOrderMapper seckingOrderMapper;

    @Autowired
    RedisTemplate redisTemplate;


    //成功->orderId， 失败->-1  ,排队中->0
    @Override
    public Long getResult(User user, Long goodsId) {
        LambdaQueryWrapper<SeckingOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SeckingOrder::getUserId,user.getId())
                        .eq(SeckingOrder::getGoodsId,goodsId);
        SeckingOrder seckingOrder = seckingOrderMapper.selectOne(queryWrapper);

//        如果数据库中存在订单则返回
        if(seckingOrder!=null){
            return seckingOrder.getOrderId();
//         如果不存在则查询 redis中有没有创建订单的数据
        }else if(redisTemplate.hasKey("isStockEmpty:"+goodsId)){
                return -1l;
        }else{
            return 0l;
        }
    }

    //根据用户Id查询订单
    @Override
    public SeckingOrder getSeckingOrderById(Long userId) {
        LambdaQueryWrapper<SeckingOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SeckingOrder::getUserId,userId);
        return  seckingOrderMapper.selectOne(queryWrapper);
    }
}
